import React, { Component } from 'react';
import httpFetch from "share/httpFetch";
import config from "config";
import { message } from 'antd';
import {messages} from "share/common";
import LabelInputOnlyRead from "./label-input-only-read";

const WrapperSelectEmployeeGroup = SelectEmployeeGroup =>
  class extends Component {

    state = {// 左边代表-->待选区，右边代表-->使用区
      isShowModal: false,// 是否显示modal
      leftWaitSelectOptions:[],// 左边待选项数组
      rightWaitSelectOptions:[],// 右边带选项数组
      leftSelectedData:[],//  左边已选数据
      rightSelectedData:[],//  右边已选数据
      leftSearchResult:[],//   左边搜所结果（加搜所结果是为了不影响左边真正的待选数据）
      rightSearchResult:[],//  右边搜所结果
      leftIndent:false,    //  左边全选样式控制
      leftAllChecked:false,//  左边是否全选
      rightIndent:false,//     右边全选样式
      rightAllChecked:false,// 右边是否全选
    }

    allData = {};         // 接口拿到的所有数据
    isLeftSearch = false;//  标记左边是否在搜所，如果是则显示搜所结果而不是显示所有待选数据，下同
    leftKeyWord = '';   //   左边搜所的关键字值，是为了把搜所结果的已选项移动到右边后刷新左边数据，下同
    isRightSearch = false;// 标记右边是否在搜所
    rightKeyWord = '';    // 右边搜所的关键字值
    leftCurrentOld = [];//   当前左边初始数据，为了取消还原操作
    rightCurrentOld = [];//  当前右边初始数据，为了取消还原操作

    componentWillMount(){
      this.getList();// 获取数据
    }

    getList = () => {
      const { leftWaitSelectOptions, rightWaitSelectOptions} = this.state;
      const { mode, newUrl, value, checkItemRender, disabledKey } = this.props;

      let disabledKeyIsFunc = false;
      let selectedData = (value && value.length) > 0 ? value : [];
      let url = newUrl ? `${config.baseUrl}${newUrl}` : `${config.baseUrl}/api/user/groups/company?page=0&size=1000`;
      if(disabledKey && typeof disabledKey === "function"){
        disabledKeyIsFunc = true;
      }

      httpFetch.get(url).then(res => {
        if(res.status === 200){
          this.allData = res.data;
          res.data.map(item => {
            let isRight = false;
            selectedData.forEach(init => {
              if(item[mode.key] === init){
                isRight = true;
                rightWaitSelectOptions.push({
                  label:checkItemRender ? checkItemRender(item) : item[mode.label],
                  value:item[mode.key],
                  disabled: disabledKeyIsFunc ? disabledKey(item) : disabledKey ? item[disabledKey] : false,
                })
              }
            })
            if(!isRight){
              leftWaitSelectOptions.push({
                label:checkItemRender ? checkItemRender(item) : item[mode.label],
                value:item[mode.key],
                disabled: disabledKeyIsFunc ? disabledKey(item) : disabledKey ? item[disabledKey] : false,
              })
            }
          })
          this.leftCurrentOld = leftWaitSelectOptions.concat(this.leftCurrentOld);
          this.rightCurrentOld = rightWaitSelectOptions.concat(this.rightCurrentOld);
          this.setState({leftWaitSelectOptions, rightWaitSelectOptions});
        }
      })
    }

    // 生成最新的props属性值
    getNewProps = () => {
      const { isShowModal, leftWaitSelectOptions, rightWaitSelectOptions, leftSelectedData, rightSelectedData,
        leftSearchResult, rightSearchResult, leftIndent, leftAllChecked, rightIndent, rightAllChecked } = this.state;
      const { modalTitle } = this.props;
      const newProps = {
        modalOption:{// modal 组件配置项
          width:'70%',
          title:modalTitle ? modalTitle : messages('components.key552'/*选择人员组*/),
          visible: isShowModal,
          onCancel: this.closeModal,
          onOk:this.onChange,
        },
        leftSelectOptions:{// 左边CheckboxGroup组件配置项
          value:leftSelectedData,
          options:this.isLeftSearch ? leftSearchResult : leftWaitSelectOptions,
          onChange:this.leftCheckBoxChange,
        },
        rightSelectOptions:{// 右边CheckboxGroup组件配置项
          value:rightSelectedData,
          options:this.isRightSearch ? rightSearchResult : rightWaitSelectOptions,
          onChange:this.rightCheckBoxChange,
        },
        leftSearch:{// 左边Search组件配置项
          onChange:this.searchLeft
        },
        rightSearch:{// 右边Search组件配置项
          onChange:this.searchRight
        },
        sendButton:{// 加入使用Button组件配置项
          disabled:leftSelectedData.length === 0,
          onClick: this.sendLeftToRight,
        },
        backButton:{// 返回待选Button组件配置项
          disabled:rightSelectedData.length === 0,
          onClick: this.sendRightToLeft,
        },
        leftAllCheckedOption:{// 左边全选Checkbox组件配置项
          onChange:this.leftCheckedAll,
          indeterminate:leftIndent,
          checked:leftAllChecked,
        },
        rightAllCheckedOption:{// 右边全选Checkbox组件配置项
          onChange:this.rightCheckedAll,
          indeterminate:rightIndent,
          checked:rightAllChecked,
        },
      }
      return Object.assign({},newProps,this.props);
    }

    // 左边全选
    leftCheckedAll = (eve) => {
      const { leftWaitSelectOptions, leftSearchResult } = this.state;
      let checked = eve.target.checked;
      let checkedList = [];
      if(checked){
        checkedList = this.isLeftSearch ? leftSearchResult.map(i => i.value) : leftWaitSelectOptions.map(i => i.value);
      }
      this.setState({leftSelectedData: checkedList,leftAllChecked: checked, leftIndent:false})
    }

    //右边全选
    rightCheckedAll = (eve) => {
      const { rightWaitSelectOptions, rightSearchResult } = this.state;
      let checked = eve.target.checked;
      let checkedList = [];
      if(checked){
        checkedList = this.isRightSearch ? rightSearchResult.map(i => i.value) : rightWaitSelectOptions.map(i => i.value);
      }
      this.setState({rightSelectedData: checkedList,rightAllChecked: checked, rightIndent:false})
    }

    // 左边带选项改变回调
    leftCheckBoxChange = (values) => {
      const { leftWaitSelectOptions } = this.state;
      this.setState({
        leftSelectedData:values,
        leftAllChecked: values.length === leftWaitSelectOptions.length,
        leftIndent:!!values.length && (values.length < leftWaitSelectOptions.length),
      });
    }

    // 右边带选项改变回调
    rightCheckBoxChange = (values) => {
      const { rightWaitSelectOptions } = this.state;
      this.setState({
        rightSelectedData:values,
        rightAllChecked: values.length === rightWaitSelectOptions.length,
        rightIndent:!!values.length && (values.length < rightWaitSelectOptions.length),
      });
    }

    // 添加到使用  按钮回调
    sendLeftToRight = () => {
      const { leftSelectedData, rightWaitSelectOptions, leftWaitSelectOptions } = this.state;
      let rightOptions = [];
      const left = leftWaitSelectOptions.filter(item => {
        let isDelete = true;
        for(let i=0; i<leftSelectedData.length; i++){
          if(item.value === leftSelectedData[i]){
            isDelete = false;
            rightOptions.push(item);
            break;
          }
        }
        return isDelete;
      });
      this.setState({
        leftAllChecked: false,
        leftIndent: false,
        leftSelectedData:[],
        rightWaitSelectOptions:rightOptions.concat(rightWaitSelectOptions),
        leftWaitSelectOptions: left,
      },()=>{
        this.isLeftSearch && this.searchLeft({target:{value:this.leftKeyWord}});
      })

    }

    // 返回待选  按钮回调
    sendRightToLeft = () => {
      const { rightSelectedData, leftWaitSelectOptions, rightWaitSelectOptions } = this.state;
      let leftOptions = [];
      const right = rightWaitSelectOptions.filter(item => {
        let isDelete = true;
        for(let i=0; i<rightSelectedData.length; i++){
          if(item.value === rightSelectedData[i]){
            isDelete = false;
            leftOptions.push(item);
            break;
          }
        }
        return isDelete;
      });
      this.setState({
        rightAllChecked: false,
        rightIndent: false,
        rightSelectedData:[],
        leftWaitSelectOptions:leftOptions.concat(leftWaitSelectOptions),
        rightWaitSelectOptions: right,
      },()=>{
        this.isRightSearch && this.searchRight({target:{value:this.rightKeyWord}});
      })
    }

    // 左边搜所会回调
    searchLeft = (eve) => {
      const { leftWaitSelectOptions } = this.state;
      let isTip = false;
      const result = leftWaitSelectOptions.filter(item => {
        if(typeof item.label === "string"){
          return item.label.includes(eve.target.value);
        }else if(item.label.key){
          return item.label.key.includes(eve.target.value);
        }else{
          isTip = true;
          return true;
        }
      });

      if(isTip){
        message.error('checkItemRender外接函数返回的元素结构最外层未设置key，且key值需与显示值相等。')
        return;
      }
      this.setState({leftSearchResult: result,leftSelectedData:[]});

      if(eve.target.value === ''){
        this.isLeftSearch = false;
      }else{
        this.isLeftSearch = true;
        this.leftKeyWord = eve.target.value;
      }
    }

    // 右边搜所回调
    searchRight = (eve) => {
      const { rightWaitSelectOptions } = this.state;
      let isTip = false;
      const result = rightWaitSelectOptions.filter(item => {
        if(typeof item.label === "string"){
          return item.label.includes(eve.target.value);
        }else if(item.label.key){
          return item.label.key.includes(eve.target.value);
        }else{
          isTip = true;
          return true;
        }
      });
      if(isTip){
        message.error('checkItemRender外接函数返回的元素结构最外层未设置key，且key值需与显示值相等。')
        return;
      }
      this.setState({rightSearchResult: result,rightSelectedData:[]});

      if(eve.target.value === ''){
        this.isRightSearch = false;
      }else{
        this.isRightSearch = true;
        this.rightKeyWord = eve.target.value;
      }
    }

    closeModal = () => {
      this.setState({
        isShowModal: false,
        leftWaitSelectOptions: this.leftCurrentOld,
        rightWaitSelectOptions: this.rightCurrentOld,
      });
    }

    toShowModal = () => {
      this.setState({isShowModal: true});
    }

    onChange = () => {
      const { mode, entity, onOk, onChange } = this.props;
      const { rightWaitSelectOptions, leftWaitSelectOptions } = this.state;
      let returnValues = [];
      if(entity){// 返回完整item数组
        rightWaitSelectOptions.map(item => {
          for(let i=0;i<this.allData.length;i++){
            if(this.allData[i][mode.key] === item.value){
              returnValues.push(this.allData[i]);
              break;
            }
          }
        })
      }else{// 返回mode中key对应的值数组
        returnValues = rightWaitSelectOptions.map(item => item.value);
      }
      onOk ? onOk(returnValues) : onChange(returnValues);
      this.setState({isShowModal: false});
      this.leftCurrentOld = leftWaitSelectOptions.concat([]);
      this.rightCurrentOld = rightWaitSelectOptions.concat([]);
    }

    render(){
      const newProps = this.getNewProps();
      const { rightWaitSelectOptions } = this.state;
      const lIOROption = {labels: rightWaitSelectOptions, onClick: this.toShowModal}
      return (
        <div>
          <LabelInputOnlyRead {...lIOROption}/>
          <SelectEmployeeGroup {...newProps}/>
        </div>
      )
    }
  }

export default WrapperSelectEmployeeGroup;
